import extend from 'extend'
import { modal } from 'vue-strap'
import { showMsg, updateMiniBanner } from '../../../vuex/action'

const validation = {
  banner(data) {
    for (let name in data) {
      if (name === 'type' && data[name] < 0) {
        return false
      }
      if (name !== 'file' && (data[name] + '').length === 0) {
        return false
      }
    }
    return true
  }
}

export default {
  name: 'MiniBannerUpdate',
  components: {
    'vue-modal': modal
  },
  props: ['banner'],
  data() {
    return {
      showUpdateModal: false
    }
  },
  vuex: {
    actions: {
      xShowMsg: showMsg,
      xUpdateMiniBanner: updateMiniBanner
    }
  },
  methods: {
    showBanner() {
      this.showUpdateModal = true
    },
    submit() {
      var formData = new FormData()
      var banner = extend(true, {}, this.banner)
      var valid = validation.banner(banner)

      if (!valid) {
        return this.xShowMsg({
          type: 'danger',
          content: '* 标记的均为必填/必选项'
        })
      }

      banner.type = +banner.type
      banner.forceExternalBrowser = +banner.forceExternalBrowser
      for (let name in banner) {
        if (name !== 'file') {
          formData.append(name, banner[name])
        }
      }
      formData.append('file', this.$els.file.files[0])

      this.xUpdateMiniBanner(formData)
        .then(() => {
          this.showUpdateModal = false
        })
        .catch((res) => {
          this.xShowMsg({
            type: 'danger',
            content: res.error_msg
          })
        })
    }
  }
}
